package com.demo.demo.controller;

import com.demo.demo.bean.QueryInfo;
import com.demo.demo.bean.ResponseResult;
import com.demo.demo.bean.User;
import com.demo.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;

import java.beans.Transient;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserDao userDao;
    @RequestMapping("/allUser")
    public String getUserList(QueryInfo QueryInfo){
        int numbers = userDao.getUserCount("%"+QueryInfo.getQuery()+"%");
        int pageStart =(QueryInfo.getPageNum()-1)*QueryInfo.getPageSize();
        List<User> users = userDao.getAllUser(QueryInfo.getQuery(), pageStart, QueryInfo.getPageSize());
        HashMap<String,Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",users);
        String res_string = JSON.toJSONString(res);
        return res_string;
    }
    @PostMapping("/user/add")
    public ResponseResult addUser(@RequestBody User user) {
        try {
            int result = userDao.insertUser(user);
            if (result > 0) {
                return new ResponseResult(200, "用户添加成功", null,0);
            } else {
                return new ResponseResult(500, "用户添加失败",  null,0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, "服务器内部错误", null,0);
        }
    }
        @GetMapping("/user/{id}")
        public String getUserById(@PathVariable int id) {
            User user = userDao.getUserById(id);
            if (user != null) {
                return "{\"code\": 200, \"data\": " + JSON.toJSONString(user) + "}";
            } else {
                return "{\"code\": 404, \"message\": \"用户不存在\"}";
            }
        }
        @RequestMapping(value = "/user/update", method = RequestMethod.OPTIONS)
        public ResponseEntity<?> handleOptions() {
            return ResponseEntity.ok().build();
        }
        @PostMapping("/user/update")
        @Transactional
        public String updateUser(@RequestBody User user) {
            int result = userDao.updateUser(user);
            if (result > 0) {
                return "{\"code\": 200, \"message\": \"更新成功\"}";
            } else {
                return "{\"code\": 500, \"message\": \"更新失败\"}";
            }
        }
        @DeleteMapping("/user/delete/{id}")
        public String deleteUser(@PathVariable int id) {
            int result = userDao.deleteUser(id);
            if (result > 0) {
                return "{\"code\": 200, \"message\": \"删除成功\"}";
            } else {
                return "{\"code\": 500, \"message\": \"删除失败\"}";
            }
        }


}
